package com.oauth.service.application.subscription.dao;

import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.oauth.service.application.subscription.beans.MemberApplicationRelation;
import com.oauth.service.jdosupport.PMF;

public class ApplicationSubscriptionDAOImpl implements ApplicationSubscriptionDAO {

	public MemberApplicationRelation addMemberToApplication(Long pMemberId, Long pApplicationId) {
		PersistenceManager persistenceManager = PMF.get().getPersistenceManager();
		MemberApplicationRelation memberApplications = null;
		try {
			memberApplications = getMemberApplications(pMemberId, persistenceManager);
			if (memberApplications == null) {
				memberApplications = new MemberApplicationRelation(pMemberId, new HashSet<Long>());
			}

			memberApplications.setLastUpdateDate(new Date());
			memberApplications.addApplication(pApplicationId);

			memberApplications = persistenceManager.makePersistent(memberApplications);

		} finally {
			persistenceManager.close();
		}
		return memberApplications;
	}

	public MemberApplicationRelation removeMemberToApplication(Long pMemberId, Long pApplicationId) {
		PersistenceManager persistenceManager = PMF.get().getPersistenceManager();
		MemberApplicationRelation memberApplications = null;
		try {
			memberApplications = getMemberApplications(pMemberId, persistenceManager);
			if (memberApplications == null) {
				memberApplications = new MemberApplicationRelation(pMemberId, new HashSet<Long>(1));
			}

			memberApplications.setLastUpdateDate(new Date());
			memberApplications.removeApplication(pApplicationId);

			memberApplications = persistenceManager.makePersistent(memberApplications);

		} finally {
			persistenceManager.close();
		}
		return memberApplications;
	}

	public MemberApplicationRelation getMemberApplications(Long pMemberId) {
		PersistenceManager persistenceManager = PMF.get().getPersistenceManager();
		try {
			return getMemberApplications(pMemberId, persistenceManager);
		} finally {
			persistenceManager.close();
		}
	}

	@SuppressWarnings("unchecked")
	private MemberApplicationRelation getMemberApplications(Long pMemberId,
			PersistenceManager pPersistanceManager) {
		List<MemberApplicationRelation> results = null;

		Query query = pPersistanceManager.newQuery(MemberApplicationRelation.class);
		query.setFilter("memberId == memberIdParam");
		query.declareParameters("Long memberIdParam");
		results = (List<MemberApplicationRelation>) query.execute(pMemberId);
		if (results == null || results.isEmpty()) {
			return null;
		}
		return results.get(0);
	}

}
